package com.ruoyi.project.jxy.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.UUID;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.jxy.domain.DownloadHistory;
import com.ruoyi.project.jxy.domain.TalkingDictRecord;
import com.ruoyi.project.jxy.service.IDownloadHistoryService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.jxy.domain.AlignedCorpusRecord;
import com.ruoyi.project.jxy.service.IAlignedCorpusRecordService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 对齐语料Controller
 *
 * @author ruoyi
 * @date 2020-09-09
 */
@RestController
@RequestMapping("/jxy/alignedCorpus")
public class AlignedCorpusRecordController extends BaseController {
    @Autowired
    private IAlignedCorpusRecordService alignedCorpusRecordService;
    @Autowired
    private IDownloadHistoryService downloadHistoryService;

    /**
     * 查询对齐语料列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:alignedCorpus:list')")
    @GetMapping("/list")
    public TableDataInfo list(AlignedCorpusRecord alignedCorpusRecord) {
        startPage();
        QueryWrapper<AlignedCorpusRecord> queryWrapper = new QueryWrapper<AlignedCorpusRecord>();
        if (StringUtils.isNotBlank(alignedCorpusRecord.getTheme())) {
            queryWrapper.eq("theme", alignedCorpusRecord.getTheme());
        }
        if (StringUtils.isNotBlank(alignedCorpusRecord.getName())) {
            queryWrapper.like("name", alignedCorpusRecord.getName());
        }
        if (StringUtils.isNotBlank(alignedCorpusRecord.getSex())) {
            queryWrapper.eq("sex", alignedCorpusRecord.getSex());
        }
        if (alignedCorpusRecord.getAge() != null) {
            queryWrapper.eq("age", alignedCorpusRecord.getAge());
        }
        if (StringUtils.isNotBlank(alignedCorpusRecord.getContent())) {
            queryWrapper.like("content", alignedCorpusRecord.getContent());
        }
        List<AlignedCorpusRecord> list = alignedCorpusRecordService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 导出对齐语料列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:alignedCorpus:export')")
    @Log(title = "对齐语料", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AlignedCorpusRecord alignedCorpusRecord) {
        QueryWrapper<AlignedCorpusRecord> queryWrapper = new QueryWrapper<AlignedCorpusRecord>(alignedCorpusRecord);
        List<AlignedCorpusRecord> list = alignedCorpusRecordService.list(queryWrapper);
        ExcelUtil<AlignedCorpusRecord> util = new ExcelUtil<AlignedCorpusRecord>(AlignedCorpusRecord.class);
        return util.exportExcel(list, "alignedCorpus");
    }

    /**
     * 获取对齐语料详细信息
     */
    @PreAuthorize("@ss.hasPermi('jxy:alignedCorpus:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(alignedCorpusRecordService.getById(id));
    }

    /**
     * 新增对齐语料
     */
    @PreAuthorize("@ss.hasPermi('jxy:alignedCorpus:add')")
    @Log(title = "对齐语料", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AlignedCorpusRecord alignedCorpusRecord) {
        alignedCorpusRecord.setCreateTime(new Date());
        alignedCorpusRecord.setCreateUser(SecurityUtils.getUsername());
        return toAjax(alignedCorpusRecordService.save(alignedCorpusRecord) ? 1 : 0);
    }

    /**
     * 修改对齐语料
     */
    @PreAuthorize("@ss.hasPermi('jxy:alignedCorpus:edit')")
    @Log(title = "对齐语料", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AlignedCorpusRecord alignedCorpusRecord) {
        alignedCorpusRecord.setUpdateTime(new Date());
        alignedCorpusRecord.setUpdateUser(SecurityUtils.getUsername());
        return toAjax(alignedCorpusRecordService.updateById(alignedCorpusRecord) ? 1 : 0);
    }

    /**
     * 删除对齐语料
     */
    @PreAuthorize("@ss.hasPermi('jxy:alignedCorpus:remove')")
    @Log(title = "对齐语料", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(alignedCorpusRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 导出发音词典数据
     */
    @PreAuthorize("@ss.hasPermi('jxy:alignedCorpus:zip')")
    @Log(title = "语音识别打包", businessType = BusinessType.OTHER)
    @GetMapping("/zip")
    public AjaxResult zip(AlignedCorpusRecord alignedCorpusRecord) {
        QueryWrapper<AlignedCorpusRecord> queryWrapper = new QueryWrapper<AlignedCorpusRecord>();
        if (StringUtils.isNotBlank(alignedCorpusRecord.getTheme())) {
            queryWrapper.eq("theme", alignedCorpusRecord.getTheme());
        }
        if (StringUtils.isNotBlank(alignedCorpusRecord.getSex())) {
            queryWrapper.eq("sex", alignedCorpusRecord.getSex());
        }
        if (StringUtils.isNotBlank(alignedCorpusRecord.getName())) {
            queryWrapper.like("name", alignedCorpusRecord.getName());
        }
        if (alignedCorpusRecord.getAge() != null) {
            queryWrapper.eq("age", alignedCorpusRecord.getAge());
        }
        if (StringUtils.isNotBlank(alignedCorpusRecord.getContent())) {
            queryWrapper.like("content", alignedCorpusRecord.getContent());
        }

        List<AlignedCorpusRecord> list = alignedCorpusRecordService.list(queryWrapper);
        DownloadHistory downloadHistory = new DownloadHistory();
        BeanUtil.copyProperties(alignedCorpusRecord, downloadHistory);
        downloadHistory.setId(null);
        downloadHistory.setType("3");
        downloadHistory.setCreateUser(SecurityUtils.getUsername());
        downloadHistory.setCreateTime(new Date());
        downloadHistoryService.save(downloadHistory);
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                String baseDir = RuoYiConfig.getProfile();
                //打包的文件夹名称
                String fileName = DateUtils.dateTimeNow();
                String fileDir = baseDir + "/download/" + fileName;
                String wavPath = fileDir + "/wav";
                String txtPath = fileDir + "/txt";
                //新建txt 文件夹
                FileUtil.mkdir(txtPath);
                for (AlignedCorpusRecord record :
                        list) {
                    //复制文件
                    //每一个文件的真实地址
                    String name = UUID.randomUUID().toString().replace("-", "");
                    //生成txt 文件
                    FileUtil.writeString(record.getContent(), FileUtil.newFile(txtPath + "/" + name + ".txt"), Charset.defaultCharset());
                }
                File zip = ZipUtil.zip(fileDir);
                //压缩包真实名称
                String zipPath = zip.getAbsolutePath();
                String zipName = zip.getName();
                //转换为可下载路径
                String downloadPath = zipPath.replace(baseDir, "/profile");
                downloadHistory.setPath(downloadPath);
                downloadHistory.setDisplayName(zipName);
                downloadHistoryService.updateById(downloadHistory);
            }
        });
        return AjaxResult.success();
    }
}
